package com.travel.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.travel.commons.shiro.ShiroUserGetter;
import com.travel.commons.utils.DesensitizeUtils;
import com.travel.commons.utils.PageUtils;
import com.travel.modules.sys.dao.SysUserDao;
import com.travel.modules.sys.dto.UserDTO;
import com.travel.modules.sys.entity.SysUser;
import com.travel.modules.sys.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Service("SysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements SysUserService {
    @Resource
    private SysUserDao sysUserDao;

    @Override
    public PageUtils getUserPage(Map<String, Object> param) {
        int page = param.get("page") == null ? 1 : (int) param.get("page");
        int limit =  param.get("limit") == null ? 10 : (int) param.get("limit");

        List<UserDTO> list = sysUserDao.queryAllUsers(param);

        return PageUtils.getPage(list, limit, page);
    }

    @Override
    public UserDTO getUserInfoByLoginName(String loginName) {
        SysUser user = sysUserDao.selectOne(new QueryWrapper<SysUser>().eq("mobile", loginName));
        if (user == null) {
            return new UserDTO();
        }
        return UserDTO.builder()
                .loginName(user.getLoginName())
                .username(user.getUsername())
                .headUrl(user.getHeadUrl())
                .roleId(user.getRoleId()).build();
    }

    @Override
    public UserDTO getUserInfo(Integer id) {
        UserDTO user = sysUserDao.getUserInfo(id);
        Integer currLoginId = ShiroUserGetter.getUserId();
        /* 如果查询用户是自己 */
        if (currLoginId.compareTo(id) == 0) {
            return user;
        }
        /* 脱敏 */
        /* 获取当前登录用户 */
        SysUser currLoginUser = sysUserDao.selectById(currLoginId);
        if (currLoginUser.getRoleId() != 1 && user.getRoleId() == 3) {// 当前登录用户不是系统管理员，并且查询的用户是普通旅客
            user.setMobile(DesensitizeUtils.run(user.getMobile(), 4, 4, "*"));
            user.setIdCard(DesensitizeUtils.run(user.getIdCard(), 7, "*"));
            user.setRealName(DesensitizeUtils.run(user.getRealName(), 2, "*"));
            user.setAge(Integer.valueOf(DesensitizeUtils.run(user.getAge().toString(), "*")));
            user.setEmail(DesensitizeUtils.run(user.getEmail(), 1, user.getEmail().indexOf("@") + 1,"*"));
        }
        return user;
    }

    @Override
    public List<UserDTO> ftQueryUsers(String[] keywords) {
        return sysUserDao.ftQueryUsers(keywords);
    }
}
